import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import {
  getPage,
  getImage
} from '../../utils/config';
import {
  http,
  promisify,
  $empty,
  $toast,
  $loading,
  Validate
} from '../../utils/utils.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cur_id: 0,
    coupon_id: 0,
    list: [],
    price: 0,
    url: api.domain,
    isSelectCoupon: false,
    coupon_price: 0
  },

  onClick(event) {
    const {
      name,
      price
    } = event.currentTarget.dataset;
    let plat_coupons = this.data.plat_coupons;
    let couponList = plat_coupons.filter(f => f.adid == name);
    var coupon_text = undefined;
    var coupon_id = undefined;
    var coupon_price = undefined;
    if (couponList.length > 0) {
      coupon_text = '-￥' + couponList[0].price
      coupon_id = couponList[0].Id
      coupon_price = couponList[0].price
    } else {
      coupon_text = '暂无可用优惠券'
      coupon_id = 0
      coupon_price = 0
    }
    this.setData({
      cur_id: name,
      price: price,
      couponList,
      coupon_id,
      coupon_price,
      coupon_text: coupon_text,
    });
  },
  /**
   * 确认支付
   */
  paymentClick() {
    const {
      cur_id,
      userId,
      coupon_id
    } = this.data;
    this.getLoginCode().then((res) => {
      http.post(api.default, {
        data: {
          action: 'pay_data',
          type: 'adorders',
          id: cur_id,
          couponid: coupon_id,
          code: res,
          userid: userId
        }
      }).then((res) => {
        const {
          data
        } = res.data;
        if (res.data.code == 0) {
          const {
            sumPrice,
            source,
            orderId
          } = this.data;
          let result = -1;

          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success(e) {
              result = 1;
            },
            fail(e) {
              result = 0;
            },
            complete() {
              let pages = null;

              //如果来自我的订单或订单详情 && 付款成功
              if (source > 0 && result == 1) {
                pages = getCurrentPages()[getCurrentPages().length - 2];
              }
              wx.redirectTo({
                url: `${getPage.paymentFeedback}?result=${result}&sumTotal=${data.orderAmount}&source=${source}&orderSn=${data.ordersn}`,
                success() {
                  if (pages != undefined || pages != null) {
                    console.log(orderId);
                    pages.paymentUpdate(orderId);
                  }
                }
              });
            }
          });
        } else {
          $toast(res.data.errmsg);
        }
      })
    });
  },

  /**
   * 获取code
   */
  getLoginCode() {
    return new Promise((resolve) => {
      promisify(wx.checkSession)().then(() => {
        resolve(resCode);
      }).catch(() => {
        promisify(wx.login)().then((res) => {
          resolve(res.code);
        });
      });
    });
  },

  // 详情图片
  showdetail(e) {
    var index = e.target.dataset.index;
    var list = this.data.list;
    for (var i = 0; i < list.length; i++) {
      if (i == index) {
        if (list[i].show)
          list[i].show = false;
        else
          list[i].show = true;
      } else
        list[i].show = false;
    }
    this.setData({
      list: list
    })
  },

  // 查看大图
  viewImg(e) {
    let url = api.imageCdn + e.currentTarget.dataset.imgurl
    wx.previewImage({
      urls: [url],
      current: url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },

  showCoupon() {
    this.setData({
      isSelectCoupon: true
    })
  },

  onClose() {
    this.setData({
      isSelectCoupon: false
    })
  },

  onCouponChange(event) {
    console.log(event)
    this.setData({
      coupon_id: event.detail,
    });
  },

  onCouponClick(event) {
    const {
      name,
      price
    } = event.currentTarget.dataset;
    this.setData({
      coupon_id: name,
      coupon_price: price
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    //获取用户登录
    let res = await app.getLogin()
    const {
      user
    } = res.data;
    this.setData({
      userId: user.user_id
    })
    //第二部分数据
    let {
      userId
    } = this.data
    http.post(api.default, {
      data: {
        action: 'getaditems',
        userId: userId
      }
    }, false).then(res => {
      console.log('putindata:', res.data.data)
      const list = res.data.data.list;
      const plat_coupons = res.data.data.plat_coupons;

      let curId = list[0].id;
      let couponList = plat_coupons.filter(f => f.adid == curId);
      var coupon_text = undefined;
      if (couponList.length > 0) {
        coupon_text = '-￥' + couponList[0].price
      } else {
        coupon_text = '暂无可用优惠券'
      }
      this.setData({
        list: list,
        couponList: couponList,
        plat_coupons: plat_coupons, //优惠券原始数据
        cur_id: list[0].id,
        price: list[0].price,
      })
      if (couponList.length > 0) {
        this.setData({
          coupon_id: couponList[0].Id,
          coupon_price: couponList[0].price,
          coupon_text: coupon_text,
        })
      }
      console.log('couponList==', couponList)
      console.log('coupon_id==', this.data.coupon_id)
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
})